package vigo_tool

import (
	"net"
	"strings"

	"permission/config"
	"permission/vigo_loger"
)

func IpInNet(ip, network string) bool {
	ipv4 := net.ParseIP(ip)
	_, subnet, err := net.ParseCIDR(network)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error() + "{ip:" + ip + ", network:" + network + "}")
		return true
	}
	if subnet.Contains(ipv4) {
		return true
	}
	return false
}

func IpInBatchNet(ip string, networks []string) bool {
	for _, network := range networks {
		if IpInNet(ip, network) {
			return true
		}
	}

	return false
}

func consulToNet(consulData string) []string {
	return strings.Split(consulData, ":")
}

// nginx ip   remote ip
func GdIpWhitelist(ips ...string) bool {
	if config.VigoDebug {
		return true
	}
	ipStrs := config.GetIpWhiterList()
	ipSlice := consulToNet(ipStrs)

	for _, val := range ips {
		if !IpInBatchNet(val, ipSlice) {
			return false
		}
	}

	return true
}
